<template>
  <div class="header">
    <span class="sys-name">
      <router-link :to="{ name: 'Home' }">社团管理系统后台</router-link>
    </span>
    <div class="right-menu">
      <template v-if="user.name">
        <span class="name">{{ user.name }}，你好</span>
        <span @click="logout" class="logout">退出</span>
      </template>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import axios from "axios";
import VueCookies from "vue-cookies";

const OK = 200;
const router = useRouter();
const user = ref({});

const getUser = async (token) => {
  try {
    const res = await axios.get("/api/users/getUser", {
      params: { token },
    });
    if (res.data.code === OK) {
      user.value = res.data.data;
    } else {
      ElMessage.error(res.data.message);
    }
  } catch (error) {
    console.error("获取用户信息失败:", error);
    ElMessage.error("获取用户信息失败");
  }
};

const logout = () => {
  VueCookies.remove("token");
  ElMessage.info("成功退出系统");
  router.push({ name: "Login" });
};

onMounted(() => {
  const token = VueCookies.get("token");
  console.log(token);
  getUser(token);
});
</script>

<style scoped>
.header {
  position: fixed;
  top: 0;
  left: 200px;
  right: 0;
  height: 60px;
  background-color: #2f4056;
}

.header .sys-name {
  display: block;
  height: 60px;
  width: 250px;
  line-height: 60px;
  margin-left: 20px;
  color: white;
}

.header .sys-name a {
  color: #fff;
  text-decoration: none;
  font-size: 16px;
}

.right-menu {
  width: 300px;
  height: 55px;
  line-height: 60px;
  margin-top: -60px;
  float: right;
  color: #eee;
}

.header .name {
  margin-right: 20px;
}

.logout {
  cursor: pointer;
  margin-left: 30px;
}
</style>
